#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : manager.py
@Author  : different
@Time    : 2021-8-5 16:18
@Desc    : 启动文件


python manager.py db init  初始化数据库
python manager.py db migrate 迁移
python manager.py db upgrade 执行迁移

python manager.py createsuperuser [-k 昵称 -n 用户名 -p 密码  必填] -s 1 or 0

"""
from flask import g
from flask_login import current_user
from flask_migrate import MigrateCommand
from flask_script import Manager, Shell

import settings
from apps import create_app
from apps.models.user import User
from expand import db

app = create_app()
manager = Manager(app)


@app.before_request
def before_request():
    g.user = current_user


def make_shell_context():
    return dict(app=app, db=db)


# 添加自定义命令
@manager.option('-k', '--nick', dest='nick')
@manager.option('-n', '--name', dest='name')
@manager.option('-p', '--password', dest='password')
@manager.option('-s', '--superuser', dest='superuser')
def createsuperuser(nick, name, password, superuser=0):
    """Create user"""
    if not all([nick, name, password]):
        print('参数不全')
    user = User()
    user.nickname = nick
    user.username = name
    user.set_password(password)
    user.is_superuser = bool(int(superuser))
    if user.is_superuser:
        tps = '超级管理员用户创建成功'
    else:
        tps = '普通用户创建成功'
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        print(e)
        print('创建失败')
        db.session.rollback()
        return
    print(tps)


manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('product', settings.SERVER)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
